package crm8000.Controllers

import crm8000.services.CustomerService
import crm8000.services.PermissionService
import crm8000.services.UserService
import grails.converters.JSON

class CustomerController {

	static allowedMethods = [categoryList: 'POST', editCategory: 'POST', 
		deleteCategory: 'POST', customerList: 'POST', queryData: 'POST']
	
	PermissionService permissionService
	
	UserService userService
	
	CustomerService customerService
	
    def index() { 
		if (!permissionService.hasPermission('1001')) {
			redirect controller: 'home'
		}

		[loginUserName: userService.loginUserName]
	}
	
	def categoryList() {
		def data = customerService.categoryList()
		
		render(contentType: "application/json") { array {
			for (c in data) {
				category id: c.id, code: c.code, name: c.name
			}
		}}
	}
	
	def editCategory() {
		def result = customerService.editCategory(params)
		
		render result as JSON
	}
	
	def deleteCategory() {
		def result = customerService.deleteCategory(params.id)
		
		render result as JSON
	}
	
	def customerList() {
		def data = customerService.customerList(params.id)
		
		render(contentType: "application/json") { array {
			for (c in data) {
				customer id: c.id, code: c.code, name: c.name, tel: c.tel, qq: c.qq, categoryId: c.category.id
			}
		}}
	}
	
	def editCustomer() {
		def result = customerService.editCustomer(params)
		
		render result as JSON
	}
	
	def deleteCustomer() {
		def result = customerService.deleteCustomer(params.id)
		
		render result as JSON
	}
	
	def queryData() {
		def data = customerService.queryData(params.queryKey)
		render(contentType: "application/json") { array {
			for (c in data) {
				customer id: c.id, code: c.code, name: c.name
			}
		}}
	}
}
